package com.msdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.entity.Message;
import com.msdp.entity.SeckillVoucher;
import com.msdp.mapper.MessageMapper;
import com.msdp.mapper.SeckillVoucherMapper;
import com.msdp.service.ISeckillVoucherService;
import com.msdp.service.MessageService;
import com.msdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>  implements MessageService {
    private static final String CHAT_LIST = "chat:";

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 添加用户到聊天列表
     * @param receiveUserId
     * @return
     */
    @Override
    public void chat(Long receiveUserId) {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2.将接收用户id添加至当前用户消息列表
        String sendKey = CHAT_LIST + userId;
        stringRedisTemplate.opsForSet().add(sendKey, receiveUserId.toString());
        //3. 将发送用户id添加至接收用户消息列表
        String receiveKey = CHAT_LIST + receiveUserId;
        stringRedisTemplate.opsForSet().add(receiveKey, userId.toString());
    }

    @Override
    public void sendMessage(Message message) {
        // 1. 获取发送用户id
        Long userId = UserHolder.getUser().getId();
        message.setSendUser(userId);

        // 2. 保存消息
        save(message);
    }

    /**
     * 根据接收人id获取消息列表
     * @param receiveUserId
     * @return
     */
    @Override
    public List<Message> getMessages(Long receiveUserId) {
        // 1. 获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 2. 根据发送人id和接收人id获取发送消息列表
        LambdaQueryWrapper<Message> eq1 = new LambdaQueryWrapper<Message>()
                .eq(Message::getSendUser, userId)
                .eq(Message::getReceiveUser, receiveUserId);
        //3. 根据发送人id和接收人id获取接收消息列表
        LambdaQueryWrapper<Message> eq2 = new LambdaQueryWrapper<Message>()
                .eq(Message::getSendUser, receiveUserId)
                .eq(Message::getReceiveUser, userId);


        List<Message> messags1 = list(eq1);
        List<Message> messags2 = list(eq2);
        List<Message> messages = new ArrayList<>();
        messages.addAll(messags1);
        messages.addAll(messags2);
        // 返回消息列表
        log.info(messages.toString());
        return messages.stream()
                .sorted(Comparator.comparing(Message::getCreateTime))
                .collect(Collectors.toList());
    }
}
